package logic

import (
	"baidu/models/mysql"
	"context"
	"fmt"

	"baidu/baidurpc/baidurpc"
	"baidu/baidurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ForgetPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewForgetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ForgetPasswordLogic {
	return &ForgetPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 忘记密码
func (l *ForgetPasswordLogic) ForgetPassword(in *baidurpc.ForgetPasswordRequest) (*baidurpc.ForgetPasswordResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)

	if user.ID != 0 {
		return nil, fmt.Errorf("用户不存在")
	}

	if user.Password == in.NewPassword {
		return nil, fmt.Errorf("新密码与旧密码一致，不允许修改")
	}

	if in.Password != user.Password {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	in.Password = in.NewPassword
	mysql.DB.Debug().Updates(&user)

	return &baidurpc.ForgetPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
